package samsam.util

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator 
import org.apache.commons.fileupload.FileItemStream 
import org.apache.commons.fileupload.servlet.ServletFileUpload 
import org.apache.commons.fileupload.util.Streams 

class FileUploadParam {
	
	public FileUploadParam(HttpServletRequest request, Map encoding = [:]) {
		setUploadParams request, encoding
	}
	
	private setUploadParams(HttpServletRequest request, Map encoding) {
		
		def uploads = [:]
		def count = 0
		
		try { 
			ServletFileUpload upload = new ServletFileUpload();
			
			FileItemIterator it = upload.getItemIterator(request)
			
			while(it.hasNext()) {
				FileItemStream item = it.next()
				InputStream stream = item.openStream()
				
				if (uploads[item.fieldName]) { 
					if (! (uploads[item.fieldName] instanceof List )) { 
						uploads[item.fieldName] = [uploads[item.fieldName]]
					} 
				}
				
				def value = (encoding[item.fieldName]) ? Streams.asString (stream, encoding[item.fieldName]) : Streams.asString (stream);
				
				def obj = (item.isFormField()) ? [value : value, isFile : false ] :   [fileName : item.name, value : value, isFile : true];
				
				if (uploads[item.fieldName] instanceof List) { 
					uploads[item.fieldName] << obj
				} else { 
					uploads[item.fieldName] = obj
				}
				
				if (obj.isFile) { 
					count++
				}
			}
			
		} catch (Exception e) {
			println e.printStackTrace()
		} finally { 
			request.setAttribute "uploads", uploads
			request.setAttribute "uploadCount", count
		}
	}
}
